package com.hunantv.mglive.ui.live;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import mgtvcom.devsmart.android.ui.HorizontalListView;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseFragment;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.GiftDataModel;
import com.hunantv.mglive.data.GiftNumModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.data.gift.ClassifyGiftModel;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.ui.adapter.GifNumAdapter;
import com.hunantv.mglive.ui.adapter.GiftPagerAdapter;
import com.hunantv.mglive.ui.adapter.GiftStyleGridAdapter;
import com.hunantv.mglive.utils.GiftUtil;
import com.hunantv.mglive.utils.MGLiveMoneyUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.utils.UIUtil;
import com.hunantv.mglive.widget.MGridView;
import com.hunantv.mglive.widget.Toast.ConfirmDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link BaseFragment} subclass.
 */
public class GiftFragment extends BaseFragment implements ItemEvent {
    private GiftViewHolder mGiftViewHolder;//页面控件
    private TextView mTvGiftName;//礼物数量标题
    private RelativeLayout mGiftViewLayout;//礼物窗体
    private LinearLayout mGiftNumLayout;//礼物数量窗体
    private RelativeLayout mRelativeLayoutGuid;//礼物引导

    private GiftStyleGridAdapter.ViewHolder mFreeViewHolder;//免费礼物
    private GiftPagerAdapter mGiftListAdapter;//礼物显示模块的适配器
    private List<GiftNumModel> mGiftNumDataList = new ArrayList<>();//礼物数量列表
    private List<CursorView> mGiftCursorList = new ArrayList<>();//礼物指示器列表

    private GiftProgramAdapter mGiftProgramAdapter;//分类礼物适配器
    private List<ClassifyGiftModel> mClassifyGifts = new ArrayList<>();//分类礼物列表
    private int mProgramPosition = 0;//分类礼物当前选择item

    private GiftDataModel mTempGiftData;//送礼时临时存放礼物数据
    private GiftAnimData mGiftAnimData = null;//送礼动画,只有免费礼物与多个礼物才储存,普通礼物直接播放动画
    private ChatViewCallback mGiftAnimCallback;//送礼动画回调

    private StarModel mStarInfo;//艺人数据
    private ConfirmDialog mConfirmDialog;//金币不够弹窗
    private int mGoldNum = 0;//金币数

    private boolean mIsLand = false;//是否全屏
    private boolean mIsAnimGift = false;
    private boolean mIsShowGiftView = false;//礼物窗口是否显示
    private boolean IsShowGiftNumView = false;//礼物数量窗口是否显示

    /**
     * 第一次请求金币数url
     * 区分送礼后大量请求金币的接口
     * 因为普通送礼请求金币的接口只取最小值
     */
    private String URL_GET_GOLD_FIRST = BuildConfig.URL_USER_MG_MONEY + "?first";
    /**
     * 免费礼物url
     * 区分普通送礼
     */
    private String URL_SEND_FREE = BuildConfig.PAY_GIFT + "?free";

    public static final int PLAY_GIFT_ANIM = 1;//Handle通知
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == PLAY_GIFT_ANIM) {
                GiftAnimData giftAnimData = (GiftAnimData) msg.obj;
                if (mGiftAnimCallback != null && giftAnimData != null) {
                    mGiftAnimCallback.startAnim(giftAnimData.photo, giftAnimData.hots, giftAnimData.formX, giftAnimData.formY);
                }
            }
            return false;
        }
    });

    //关闭礼物窗体监听器
    private View.OnClickListener mCloseGiftViewListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mGiftNumLayout.getVisibility() == View.VISIBLE) {
                hiddenGiftNumView();
            } else {
                hideGiftView();
            }
        }
    };

    public GiftFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_gift_view, container, false);
        mGiftViewHolder = new GiftViewHolder();
        initGiftView(view);
        initGiftNumView(view);

        initDialog();
        loadMgMoney(true);
        loadFreeGiftCount();
        return view;
    }

    /**
     * 初始化礼物模块
     */
    private void initGiftView(View view) {
        mGiftViewLayout = (RelativeLayout) view.findViewById(R.id.ll_gift_content);
        mGiftViewHolder.programTitleView = (RelativeLayout) view.findViewById(R.id.ll_program_title);
        mGiftViewHolder.programTitleText = (TextView) view.findViewById(R.id.tv_program_title);
        mGiftViewHolder.programTitleLine = view.findViewById(R.id.v_program_title_line);

        mGiftViewHolder.fullGoldView = (RelativeLayout) view.findViewById(R.id.ll_full_gold);
        mGiftViewHolder.fullGoldText = (TextView) view.findViewById(R.id.tv_gift_gold_num);
        mGiftViewHolder.llProgram = (LinearLayout) view.findViewById(R.id.ll_gold_program);
        mGiftViewHolder.hlvProgram = (HorizontalListView) view.findViewById(R.id.hlv_program);
        mGiftViewHolder.programLine = view.findViewById(R.id.v_line_program);

        mGiftViewHolder.goldProGramView = (LinearLayout) view.findViewById(R.id.ll_program_gold_view);
        mGiftViewHolder.goldText = (TextView) view.findViewById(R.id.tv_gift_gold_num_program);
        mGiftViewHolder.cursorLayout = (LinearLayout) view.findViewById(R.id.ll_gift_pager_cursor);//装载指示器的layout
        mGiftViewHolder.pageGifts = (ViewPager) view.findViewById(R.id.pager_gift_list);
        mGiftListAdapter = new GiftPagerAdapter(getContext(), this, 2, 4, false, false);
        mGiftViewHolder.pageGifts.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity") || getActivity().getClass().getSimpleName().equals("FullScreenVideoActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("t", "p" + (position + 1));
                }
                updateCursor(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        mGiftViewHolder.pageGifts.setAdapter(mGiftListAdapter);
//        LinearLayout.LayoutParams mLP = (LinearLayout.LayoutParams) mGiftViewHolder.pageGifts.getLayoutParams();
//        mGiftViewHolder.pageGifts.setLayoutParams(mLP);

        //礼物窗体关闭按钮
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity") || getActivity().getClass().getSimpleName().equals("FullScreenVideoActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                }

                MGLiveMoneyUtil.getInstance().goMGLiveMonneyPay(getActivity());

            }
        };
        mGiftViewHolder.fullGoldView.setOnClickListener(listener);
        mGiftViewHolder.goldProGramView.setOnClickListener(listener);

        mGiftViewHolder.vBg = view.findViewById(R.id.v_gift_view_bg);
        mGiftViewHolder.vBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGiftNumLayout.getVisibility() == View.VISIBLE) {
                    hiddenGiftNumView();
                }
                hideGiftView();
            }
        });

        mGiftProgramAdapter = new GiftProgramAdapter(getContext());
        mGiftViewHolder.hlvProgram.setAdapter(mGiftProgramAdapter);
        mGiftViewHolder.hlvProgram.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mProgramPosition != position) {
                    updateGiftProgramSelect(position);
                    mProgramPosition = position;
                }
            }
        });
            mRelativeLayoutGuid = (RelativeLayout) view.findViewById(R.id
                    .relativelayout_perfcet_holiday_guide_portrait);
    }


    private void guide() {
        mRelativeLayoutGuid.setVisibility(View.VISIBLE);
        ImageView imageView = (ImageView) mRelativeLayoutGuid.findViewById(R.id.imageview_guide);
        Glide.with(getActivity()).load(mClassifyGifts.get(1).getClassifyIcon()).into(imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRelativeLayoutGuid.setVisibility(View.GONE);
                updateGiftProgramSelect(1);
                mProgramPosition = 1;

            }
        });
        mRelativeLayoutGuid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRelativeLayoutGuid.setVisibility(View.GONE);
            }
        });
    }

    private void initGiftNumView(View view) {
        loadGiftNumData();
        //礼物数量窗体-礼物名称
        mTvGiftName = (TextView) view.findViewById(R.id.giftNameTextView);
        //礼物数量窗体
        mGiftNumLayout = (LinearLayout) view.findViewById(R.id.view_gift_number_layout);
        //礼物数量-取消按钮
        RelativeLayout closeGiftNumView = (RelativeLayout) mGiftNumLayout.findViewById(R.id.closeGiftNumView);
        closeGiftNumView.setOnClickListener(mCloseGiftViewListener);

        ListView giftNumListView = (ListView) mGiftNumLayout.findViewById(R.id.giftNumListView);
        GifNumAdapter mGiftNumListAdapter = new GifNumAdapter(this, mGiftNumDataList);

        giftNumListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GiftNumModel giftNumData = mGiftNumDataList.get(position);
                if (giftNumData != null && mTempGiftData != null && mGiftAnimData != null && mGiftAnimData.hots != null) {
                    mGiftAnimData.hots = (Integer.parseInt(mGiftAnimData.hots) * giftNumData.getGiftNum()) + "";
                    sendChatGift(mTempGiftData, giftNumData, false);
                    //当前金币必须足够支付才播放动画
                    if (mGoldNum > mGiftAnimData.price * giftNumData.getGiftNum()) {
                        //播放动画
                        Message msg = new Message();
                        msg.what = PLAY_GIFT_ANIM;
                        msg.obj = mGiftAnimData;
                        mHandler.sendMessage(msg);
                    }
                    hiddenGiftNumView();
                }
            }
        });
        giftNumListView.setAdapter(mGiftNumListAdapter);
    }

    private void initDialog() {
        mConfirmDialog = new ConfirmDialog(getContext(), R.string.tips_not_gold, R.string.ok_1, R.string.cancel);
        mConfirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {

                MGLiveMoneyUtil.getInstance().goMGLiveMonneyPay(getActivity());

                mConfirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                mConfirmDialog.cancel();
            }
        });
    }

    /**
     * 获取礼物数据
     */
    public void loadGiftData(String starId) {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("artistId", starId)
                .build();
        post(BuildConfig.GET_CLASSIFY_GIFT_LIST, body);
    }

    /**
     * 获取免费礼物数量
     */
    public void loadFreeGiftCount() {
        if (isLogin()) {
            Map<String, String> body = new FormEncodingBuilderEx().add("uid", getUid()).add("token", getToken()).build();
            post(BuildConfig.GET_FREE_GIFT_NUM, body);
        }
    }

    /**
     * 获取我的芒果币
     */
    private void loadMgMoney(boolean isFirst) {
        if (isLogin()) {
            Map<String, String> userMoneyBody = new FormEncodingBuilderEx()
                    .add("uid", getUid())
                    .add("token", getToken())
                    .build();
            if (isFirst) {
                post(URL_GET_GOLD_FIRST, userMoneyBody);
            } else {
                post(BuildConfig.URL_USER_MG_MONEY + "?" + System.currentTimeMillis(), userMoneyBody);
            }
        }
    }

    /**
     * 获取礼物数量数据
     */
    private void loadGiftNumData() {
        mGiftNumDataList = new ArrayList<>();
        GiftNumModel giftNumData1 = new GiftNumModel();
        giftNumData1.giftNum = 66;
        giftNumData1.giftNumText = "一切顺利";
        mGiftNumDataList.add(giftNumData1);

        GiftNumModel giftNumData2 = new GiftNumModel();
        giftNumData2.giftNum = 188;
        giftNumData2.giftNumText = "要抱抱";
        mGiftNumDataList.add(giftNumData2);

        GiftNumModel giftNumData3 = new GiftNumModel();
        giftNumData3.giftNum = 520;
        giftNumData3.giftNumText = "我爱你";
        mGiftNumDataList.add(giftNumData3);

        GiftNumModel giftNumData4 = new GiftNumModel();
        giftNumData4.giftNum = 10;
        giftNumData4.giftNumText = "十全十美";
        mGiftNumDataList.add(giftNumData4);
    }

    /**
     * 关闭礼物数量窗体
     */
    private void hiddenGiftNumView() {
        Animation closeGiftNumViewAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_bottom_out);
        mGiftNumLayout.setAnimation(closeGiftNumViewAnimation);
        mGiftNumLayout.setVisibility(View.GONE);//关闭礼物数量窗体
        IsShowGiftNumView = false;
        mGiftAnimData = null;//重置送礼动画
    }

    /**
     * 关闭礼物窗体
     */
    public void hideGiftView() {
        if (mIsAnimGift || !mIsShowGiftView) {
            return;
        }
        mIsAnimGift = true;
        Animation animation;
        if (!mIsLand) {
            animation = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_bottom_out);
        } else {
            animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            animation.setDuration(500);
        }
        startHideGiftViewAnim(animation);
    }

    private void startHideGiftViewAnim(Animation animation) {
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsShowGiftView = false;
                mIsAnimGift = false;
                mGiftViewLayout.setVisibility(View.INVISIBLE);
                mGiftViewHolder.vBg.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mGiftViewLayout.startAnimation(animation);
    }


    public void showGiftView() {
        if (mIsAnimGift && mIsShowGiftView) {
            return;
        }
        loadMgMoney(true);

        mIsAnimGift = true;
        Animation animation;
        if (!mIsLand) {
            animation = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_bottom_in);
        } else {
            animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            animation.setDuration(500);
        }
        startShowGiftViewAnim(animation);
    }

    private void startShowGiftViewAnim(Animation animation) {
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsShowGiftView = true;
                mIsAnimGift = false;
                mGiftViewLayout.setVisibility(View.VISIBLE);
                mGiftViewHolder.vBg.setVisibility(View.VISIBLE);


                SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences
                        (getActivity());
                if (mClassifyGifts.size() > 1 && defaultSharedPreferences.getBoolean(this.getClass()
                        .getCanonicalName(), true)) {
                    defaultSharedPreferences.edit().putBoolean(this.getClass()
                            .getCanonicalName(), false).apply();
                    guide();
                }

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mGiftViewLayout.startAnimation(animation);
    }

    /**
     * 更新礼物指示器显示状态
     */
    private void updateCursor(int n) {
        for (int i = 0; i < mGiftCursorList.size(); i++) {
            mGiftCursorList.get(i).setSelected(n == i);
        }
    }

    /**
     * 更新礼物指示器数量
     */
    private void updatGiftCursor(int n) {
        mGiftCursorList.clear();
        if (null != mGiftViewHolder.cursorLayout) {
            mGiftViewHolder.cursorLayout.removeAllViews();
            if (n > 1) {
                for (int i = 0; i < n; i++) {
                    CursorView mCursor = new CursorView(getActivity());
                    mCursor.setDefaultColor(mIsLand ? 0x33FFFFFF : 0x1A000000);
                    mGiftCursorList.add(mCursor);
                    mGiftViewHolder.cursorLayout.addView(mCursor);
                }
            }
        }
    }

    /**
     * 默认的发送礼物
     */
    private void sendChatGift(GiftDataModel giftData, boolean isFree) {
        sendChatGift(giftData, new GiftNumModel(1), isFree);
    }

    /**
     * 发送一定数量的礼物给指定的对象
     */
    private void sendChatGift(GiftDataModel giftData, GiftNumModel giftNumData, boolean isFree) {
        sendMqttMsg(ChatData.CHAT_TYPE_GIFT, giftData, giftNumData, isFree);
    }

    /**
     * 发送礼物消息
     *
     * @param type
     * @param giftData
     * @param giftNumData
     */
    private void sendMqttMsg(int type, GiftDataModel giftData, GiftNumModel giftNumData, boolean isFree) {
        //消费礼物
        try {
            if (type == ChatData.CHAT_TYPE_GIFT) {
                FormEncodingBuilderEx builder = new FormEncodingBuilderEx();
                builder.add("gid", giftData.getGid() + "");
                builder.add("count", giftNumData.getGiftNum() + "");
                builder.add("gift", "1");
                builder.add("amount", giftNumData.getGiftNum() * giftData.getPrice() + "");
                builder.add("buid", getUserInfo().getUid());
                builder.add("cuid", getStarInfo().getUid());
                builder.add("token", getUserInfo().getToken());
                String str = "送给 " + getStarInfo().getNickName();
                builder.add("tip", str);
                if (!StringUtil.isNullorEmpty(getMqttClientId())) {
                    builder.add("clientId", getMqttClientId());
                    builder.add("flag", getMqttFlag());
                    builder.add("key", getMqttKey());
                }
                if (isFree) {
                    post(URL_SEND_FREE, builder.build());
                } else {
                    post(BuildConfig.PAY_GIFT + "?" + System.currentTimeMillis(), builder.build());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.GET_CLASSIFY_GIFT_LIST.equals(url)) {
            return JSON.parseArray(resultModel.getData(), ClassifyGiftModel.class);
        } else if (URL_GET_GOLD_FIRST.equals(url)) {
            try {
                JSONObject json = new JSONObject(resultModel.getData());
                String balance = json.getString("balance");
                return balance;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else if (url.startsWith(BuildConfig.URL_USER_MG_MONEY)) {
            try {
                JSONObject json = new JSONObject(resultModel.getData());
                String balance = json.getString("balance");
                return Integer.parseInt(balance) > mGoldNum ? mGoldNum : balance;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return super.asyncExecute(url, resultModel);
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        super.onSucceed(url, resultModel);
        if (url != null) {
            if (BuildConfig.GET_CLASSIFY_GIFT_LIST.equals(url)) {
                try {
                    mClassifyGifts = (List<ClassifyGiftModel>) resultModel.getDataModel();
                    mGiftProgramAdapter.setClassifyGifts(mClassifyGifts);
                    updateGiftProgramSelect(0);
                    mProgramPosition = 0;
                    GiftUtil.getInstance().setGifts(mClassifyGifts);
//                    loadGifts();
                } catch (Exception ignored) {

                }
            } else if (url.startsWith(BuildConfig.URL_USER_MG_MONEY)) {
                //我的金币
                if (resultModel.getDataModel() != null) {
                    mGoldNum = Integer.parseInt(resultModel.getDataModel().toString());
                    mGiftViewHolder.fullGoldText.setText(mGoldNum + "");
                    mGiftViewHolder.goldText.setText(mGoldNum + "");
                }
            } else if (url.startsWith(BuildConfig.PAY_GIFT)) {
                if (URL_SEND_FREE.equals(url)) {
                    //免费礼物
                    loadFreeGiftCount();
                    //播放动画
                    Message msg = new Message();
                    msg.what = PLAY_GIFT_ANIM;
                    msg.obj = mGiftAnimData;
                    mHandler.sendMessage(msg);
                    mGiftAnimData = null;
                }
                //刷新金币
                loadMgMoney(false);
            } else if (BuildConfig.GET_FREE_GIFT_NUM.equals(url)) {
                //免费礼物数量
                JSONObject json;
                try {
                    json = new JSONObject(resultModel.getData());
                    int freeGiftCount = json.getInt("count");
                    MaxApplication.getInstance().setFreeGiftCount(freeGiftCount > 0 ? freeGiftCount : 0);
                    if (mGiftViewHolder != null && mGiftViewHolder.pageGifts != null) {
                        if (mGiftViewHolder.pageGifts.getChildCount() > 0) {
                            for (int i = 0; i < mGiftViewHolder.pageGifts.getChildCount(); i++) {
                                View view = mGiftViewHolder.pageGifts.getChildAt(i);
                                MGridView mGridView = (MGridView) view.findViewById(R.id.mgv_gift_gridview);
                                if (mGridView != null) {
                                    Adapter adapter = mGridView.getAdapter();
                                    if (adapter instanceof GiftStyleGridAdapter) {
                                        ((GiftStyleGridAdapter) adapter).notifyDataSetChanged();
                                    }
                                }
                            }
                        }
                    }


//                    if (mFreeViewHolder != null) {
//                        if (freeGiftCount <= 0) {
//                            mFreeViewHolder.mNum.setText("免费(0)");
//                            mFreeViewHolder.mAnima.startAnima();
//                            mFreeViewHolder.mAnima.showBg(true);
//                        } else {
//                            mFreeViewHolder.mNum.setText("免费(" + freeGiftCount + ")");
//                            mFreeViewHolder.mAnima.showBg(false);
//                        }
//                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        if (url.startsWith(BuildConfig.PAY_GIFT)) {
            if ("2201".equals(resultModel.getCode()) || resultModel.getMsg().startsWith("剩余金币不足")) {
                if (!mConfirmDialog.isShowing()) {
                    mConfirmDialog.show();
                }
            } else if (URL_SEND_FREE.equals(url)) {
                if ("1507".equals(resultModel.getCode())) {
                    //免费礼物出错,设置数量为0
                    MaxApplication.getInstance().setFreeGiftCount(0);
                    if (mFreeViewHolder != null) {
                        mFreeViewHolder.mNum.setText("免费(0)");
                    }
                }
                //免费礼物失败,清空动画
                mGiftAnimData = null;
            }
        } else if (!"200".equals(resultModel.getCode())) {
            //屏蔽mqtt返回参数
            Toast.makeText(getContext(), resultModel.getMsg(), Toast.LENGTH_SHORT).show();
        }
        super.onFailure(url, resultModel);

    }

    @Override
    public void onError(String url, Exception e) {
        if (URL_SEND_FREE.equals(url)) {
            //免费礼物失败,清空动画
            mGiftAnimData = null;
        }
        super.onError(url, e);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
        Adapter adapter = parent.getAdapter();
        GiftDataModel giftData = (GiftDataModel) adapter.getItem(position);
        if (giftData != null) {
            boolean isFree = false;
            if (giftData.getPrice() == 0) {
                isFree = true;
                if (mFreeViewHolder == null) {
                    if (view.getTag() instanceof GiftStyleGridAdapter.ViewHolder) {
                        mFreeViewHolder = (GiftStyleGridAdapter.ViewHolder) view.getTag();
                    }
                }
                if (MaxApplication.getInstance().getFreeGiftCount() <= 0) {
                    //没有免费礼物,不发请求
                    return;
                }
            }
            //计算动画参数
            int[] location = new int[2];
            view.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
            GiftAnimData giftAnimData = new GiftAnimData();
            giftAnimData.photo = giftData.getPhoto();
            giftAnimData.hots = giftData.getHots();
            int n = getContext().getResources().getDimensionPixelSize(R.dimen.height_5dp);
            if (mIsLand) {
                giftAnimData.formX = location[0] + (view.getMeasuredWidth() / 2);
                giftAnimData.formY = location[1] + (view.getMeasuredHeight() / (mProgramPosition == 0 ? 8 : 3));
            } else {
                giftAnimData.formX = location[0] + (view.getMeasuredWidth() / 2);
                giftAnimData.formY = location[1] + (view.getMeasuredHeight() / 4);
            }

            giftAnimData.price = giftData.getPrice();

            //金币数
            if (isFree) {
                //免费礼物发送成功才播放动画
                mGiftAnimData = giftAnimData;
            } else if (mGoldNum > giftData.getPrice()) {
                //普通礼物直接播放动画
                Message msg = new Message();
                msg.what = PLAY_GIFT_ANIM;
                msg.obj = giftAnimData;
                mHandler.sendMessage(msg);
            }
            sendChatGift(giftData, isFree);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Adapter adapter = parent.getAdapter();
        GiftDataModel giftData = (GiftDataModel) adapter.getItem(position);
        if (giftData != null && mGiftAnimData == null && giftData.getPrice() > 0) {
            int[] location = new int[2];
            view.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
            mGiftAnimData = new GiftAnimData();
            mGiftAnimData.photo = giftData.getPhoto();
            mGiftAnimData.hots = giftData.getHots();
            if (mIsLand) {
                mGiftAnimData.formX = location[0] + (view.getMeasuredWidth() / 2);
                mGiftAnimData.formY = location[1] + (view.getMeasuredHeight() / 8);
            } else {
                mGiftAnimData.formX = location[0] + (view.getMeasuredWidth() / 2);
                mGiftAnimData.formY = location[1] + view.getMeasuredHeight() / 2;
            }

            mGiftAnimData.price = giftData.getPrice();
            mTempGiftData = giftData;
            //设置礼物名称
            mTvGiftName.setText(giftData.getName());
            //使礼物数量窗体动画显示
            Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_bottom_in);
            mGiftNumLayout.setAnimation(animation);
            mGiftNumLayout.setVisibility(View.VISIBLE);
            mGiftNumLayout.setTag(giftData);
        }
        return true;
    }

    @Override
    public void onResume() {
        loadMgMoney(true);
        loadFreeGiftCount();
        super.onResume();
    }

    public void onScreenChange(boolean island) {
        mIsLand = island;
        mRelativeLayoutGuid.setVisibility(View.GONE);
        if (island) {
            //全屏
//            loadGiftData();
            mGiftViewHolder.programTitleView.setBackgroundResource(R.color.full_gift_bg);
            mGiftViewHolder.pageGifts.setBackgroundResource(R.color.full_gift_bg);
            FrameLayout.LayoutParams ps = (FrameLayout.LayoutParams) mGiftViewLayout.getLayoutParams();
            ps.width = (int) UIUtil.dip2px(getActivity(), 235f);
            ps.height = FrameLayout.LayoutParams.MATCH_PARENT;
            mGiftViewLayout.setLayoutParams(ps);
            mGiftViewHolder.llProgram.setBackgroundResource(R.color.gift_full_gold_view_bg);
            mGiftViewHolder.fullGoldView.setVisibility(View.VISIBLE);
            mGiftViewHolder.goldProGramView.setVisibility(View.GONE);
            mGiftViewHolder.programLine.setVisibility(View.GONE);
            mRelativeLayoutGuid = (RelativeLayout) getView().findViewById(R.id
                    .relativelayout_perfcet_holiday_guide_landscape);
        } else {
            //半屏
            FrameLayout.LayoutParams ps = (FrameLayout.LayoutParams) mGiftViewLayout.getLayoutParams();
            ps.width = FrameLayout.LayoutParams.MATCH_PARENT;
            ps.height = (int) UIUtil.dip2px(getActivity(), 266f);
            mGiftViewLayout.setLayoutParams(ps);
            mGiftViewHolder.programTitleView.setBackgroundResource(R.color.common_white);
            mGiftViewHolder.pageGifts.setBackgroundResource(R.color.common_white);
            mGiftViewHolder.llProgram.setBackgroundResource(R.color.gift_gold_view_bg);
            mGiftViewHolder.fullGoldView.setVisibility(View.GONE);
            mGiftViewHolder.goldProGramView.setVisibility(View.VISIBLE);
            mGiftViewHolder.programLine.setVisibility(View.VISIBLE);

            mRelativeLayoutGuid = (RelativeLayout) getView().findViewById(R.id
                    .relativelayout_perfcet_holiday_guide_portrait);
        }

        //动态修改礼物栏目及金币数布局
        mGiftViewHolder.llProgram.setWeightSum(island ? 4 : 5);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mGiftViewHolder.hlvProgram.getLayoutParams();
        layoutParams.weight = island ? 4 : 4;
        mGiftViewHolder.hlvProgram.setLayoutParams(layoutParams);
        //更新礼物栏目
        mGiftProgramAdapter.setIsLang(mIsLand);
        //更新礼物显示
        updateGiftProgramSelect(0);
        mProgramPosition = 0;
    }

    /**
     * 更新礼物列表
     * @param position
     */
    private void updateGiftProgramSelect(int position) {
        if (mClassifyGifts != null && mClassifyGifts.size() > position) {
            ClassifyGiftModel classifyGiftModel = mClassifyGifts.get(position);
            boolean isDefault = "1".equals(classifyGiftModel.getIsDefault());
            if (isDefault) {
                //默认分组
                if (mIsLand) {
                    mGiftListAdapter.setRowAndColum(3, 3);
                } else {
                    mGiftListAdapter.setRowAndColum(2, 4);
                }
                mGiftViewHolder.programTitleView.setVisibility(View.GONE);
            } else {
                if (mIsLand) {
                    mGiftListAdapter.setRowAndColum(1, 2);
                } else {
                    mGiftListAdapter.setRowAndColum(1, 3);
                }
                mGiftViewHolder.programTitleText.setText(classifyGiftModel.getGiftsTitle());
                mGiftViewHolder.programTitleText.setTextColor(Color.parseColor(mIsLand ? "#ffffff" : "#333333"));
                mGiftViewHolder.programTitleLine.setVisibility(mIsLand ? View.GONE : View.VISIBLE);
                mGiftViewHolder.programTitleView.setVisibility(View.VISIBLE);
            }
            mGiftProgramAdapter.setSelect(position);
            mGiftListAdapter.setLandAndProgram(mIsLand, !isDefault);
            mGiftListAdapter.setGiftList(classifyGiftModel.getGifts());
            mGiftListAdapter.notifyDataSetChanged();
            updatGiftCursor(mGiftListAdapter.getCount());

            mGiftViewHolder.pageGifts.setCurrentItem(0);
            updateCursor(0);
        }
    }

    /**
     * 获取艺人信息对象
     */
    public StarModel getStarInfo() {
        return mStarInfo;
    }

    /**
     * 设置艺人信息对象并更新艺人信息界面
     */
    public void setStarInfo(StarModel mStarInfo) {
        if (mStarInfo == null) {
            return;
        }
        this.mStarInfo = mStarInfo;
        loadGiftData(mStarInfo.getUid());
    }

    public void setGiftAnimListener(ChatViewCallback call) {
        mGiftAnimCallback = call;
    }

    public boolean onBackpressed() {
        if (mRelativeLayoutGuid !=null&& mRelativeLayoutGuid.getVisibility() == View.VISIBLE) {
            mRelativeLayoutGuid.setVisibility(View.GONE);
            return true;
        }
        if (IsShowGiftNumView) {
            hiddenGiftNumView();
            return true;
        }
        if (mIsShowGiftView) {
            hideGiftView();
            return true;
        }
        return false;
    }

    @Override
    public void onDestroy() {
        if (mGiftViewHolder != null && mGiftViewHolder.pageGifts != null) {
            if (mGiftViewHolder.pageGifts.getChildCount() > 0) {
                for (int i = 0; i < mGiftViewHolder.pageGifts.getChildCount(); i++) {
                    View view = mGiftViewHolder.pageGifts.getChildAt(i);
                    MGridView mGridView = (MGridView) view.findViewById(R.id.mgv_gift_gridview);
                    if (mGridView != null) {
                        Adapter adapter = mGridView.getAdapter();
                        if (adapter instanceof GiftStyleGridAdapter) {
                            ((GiftStyleGridAdapter) adapter).onDestory();
                        }
                    }
                }
            }

        }
        mGiftAnimCallback = null;
        super.onDestroy();
    }

    private class GiftAnimData {
        public String photo;
        public String hots;
        public int formX;
        public int formY;
        private long price;
    }

    class GiftViewHolder {
        View vBg;
        RelativeLayout programTitleView;
        View programTitleLine;
        TextView programTitleText;
        ViewPager pageGifts;
        LinearLayout cursorLayout;
        RelativeLayout fullGoldView;
        TextView fullGoldText;

        LinearLayout llProgram;
        LinearLayout goldProGramView;
        HorizontalListView hlvProgram;
        View programLine;
        TextView goldText;
    }
}

